package com.example.whm;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.app.ProgressDialog;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.AdapterView.OnItemSelectedListener;
import org.holoeverywhere.widget.CheckBox;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.Spinner;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;

import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.lib.CustomListView;
import com.example.whm.lib.box_Selection;
import com.example.whm.model.Address;
import com.example.whm.model.Box;

public class FourFragmentPreorder extends Fragment implements OnItemSelectedListener,OnClickListener{

	private AQuery aq; 
	private AQuery aq2;
	
	private String topic;
	Address add;
	List<Box> boxs;
	int num=0;
	int price=0;
	int tag;
	box_Selection mCallback;
	Spinner sp;
	 TextView v;
	 List<String> datelist;
	 ProgressDialog dialog;
	 adapter adapter1;
	 adapter2 adap2;
	 TextView num_t;
	 TextView price_t;
	 CustomListView listview;
	 ListView list;
	 //CheckBox checkb;
	 List<CheckBox> check_list=new ArrayList<CheckBox>();
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
    	View view = inflater.inflate(R.layout.four_layout_item, container, false); 
    	aq=new AQuery(getActivity());
    	aq2=new AQuery(getActivity(), view);
    	
    	return view;
	}






	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		init();
		
		
		
	}


  public void init(){

	  String url="http://"+Whm_app.api_url+":9000/api/buy_box?tag=2";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "ui");
	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
  	String cookiename=sp.getString("cookie_name",null);
  	String cookievalue=sp.getString("cookie_value",null);
  	if (cookiename!=null&&cookievalue!=null) {
  		cb.cookie(cookiename,cookievalue);               
	}
	  aq.ajax(cb);
  }

  public void ui(String url, String r, AjaxStatus status){
	  
	  System.out.println("ui  s="+r); 
	  if (status.getCode()==200) {
		
		  final String s=r;
		  new Thread( new Runnable() {
			  @Override
			public void run() {
				  // String s1= JSON.parseObject(s).getString("users");
				  
				  String addj= JSON.parseObject(s).getString("add");
				  String listj= JSON.parseObject(s).getString("list");
				  add= JSON.parseObject(addj, Address.class);
				  boxs= JSON.parseArray(listj, Box.class);
				  System.out.println("boxs.size()========="+boxs.size());
				  if (list!=null) {
					  num=0;
					  price=0;
				  }
				  for(Box b:boxs){
					  num=num+b.getNum();
					  price=price+b.getPrice();
					  
				  };
				  datelist=getlist_date(7);
				  getActivity().runOnUiThread(new Runnable() {
					  
					  @Override
					  public void run() {
						  if (list!=null) {
							  show_dialog(false);
							  Whm_app.newl.remove(Integer.valueOf(2));
							  num_t.setText(String.valueOf(num));
							  price_t.setText(String.valueOf(price));
							  List<List<Box>> l= new ArrayList<List<Box>>();
							  l.add(boxs);
							  adapter1.setList(l);
							  adapter1.notifyDataSetChanged();
						}else{							
							aq2.id(R.id.four_layout_progress).gone();
							aq2.id(R.id.four_layout_line).visible();
							Toast.makeText(getActivity(), "preorder visible", 1000).show();;
							
							list=(ListView) aq2.id(R.id.four_layout_detail_listview).getListView();
							View v=getActivity().getLayoutInflater().inflate(R.layout.four_layout_header, null);
							View v2=getActivity().getLayoutInflater().inflate(R.layout.four_layout_footer_preorder, null);
							AQuery a=new AQuery(v);
							AQuery a2=new AQuery(v2);
							a.id(R.id.four_layout_contact_name).text(add.getContact_name());
							a.id(R.id.four_layout_contact_phone).text(add.getPhone());
							a.id(R.id.four_layout_contact_addr).text(add.getDetail_address());
							a.find(R.id.four_layout_pay_s2).enabled(false);
							a2.find(R.id.four_layout_btn_sure).clicked(FourFragmentPreorder.this); 
							sp=(Spinner) a2.id(R.id.four_layout_footer_preorder_to).getView();
							sp.setSelection(1,true);
							sp.setOnItemSelectedListener(FourFragmentPreorder.this);  
							ArrayAdapter adapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, datelist);
							sp.setAdapter(adapter);
							
							
							list.addHeaderView(v);
							list.addFooterView(v2);
							List<List<Box>> l= new ArrayList<List<Box>>();
							l.add(boxs);
							adapter1= new adapter(l);
							aq2.id(R.id.four_layout_detail_listview).adapter(adapter1);
						}
						  //Utility.setListViewHeightBasedOnChildren(list);
					  }
				  });
			  }
		  }).start();
		  
	}
	  
  }

  
  
  public List<String> getlist_date(int len){
		List<String> list=new ArrayList<String>();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
		Calendar c = Calendar.getInstance();
		//list.add(sdf.format(c.getTime()));
		for (int i = 0; i < len; i++) {
			int day = c.get(Calendar.DATE);  
	        c.set(Calendar.DATE, day + 1);
	        list.add(sdf.format(c.getTime()));
		}
		return list;
	}
  
  
  
  
  class adapter extends BaseAdapter{

		
		List<List<Box>> list;
		
		
		
		public List<List<Box>> getList() {
			return list;
		}


		public void setList(List<List<Box>> list) {
			this.list = list;
		}


		public adapter() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		public adapter(List<List<Box>> list) {
			super();
			this.list = list;
		}

      
		
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			System.out.println("arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.four_layout_list, arg2);
			}
			
			
			List<Box> i = (List<Box>) getItem(arg0);
			AQuery aq = aq2.recycle(arg1);
			 adap2=new adapter2(i);
		   listview= (CustomListView) aq.id(R.id.four_layout_list_item_listview).getListView();
			aq.id(R.id.four_layout_list_item_listview).adapter(adap2);
			aq.id(R.id.four_layout_btn_all).clicked(FourFragmentPreorder.this);
			aq.id(R.id.four_layout_btn_del).clicked(FourFragmentPreorder.this);
			/* v = (TextView) aq.id(R.id.four_layout_text_sp).getTextView();
				v.setText("preorder");
				v.setOnClickListener(FourFragmentPreorder.this);*/
		   // sp=(Spinner) aq.id(R.id.four_layout_list_spinner).getView();
			//sp.setSelection(1,true);
			//sp.setOnItemSelectedListener(FourFragmentPreorder.this);  
		     num_t=(TextView) aq.id(R.id.four_listview_footview_num).getTextView();
		    num_t.setText(String.valueOf(num));
		     price_t=(TextView) aq.id(R.id.four_listview_footview_price).getTextView();
			price_t.setText(String.valueOf(price));
			return arg1;
		}
		
		
	}
  
  public void makeMenu(Menu menu, MenuInflater inflater) {
      if (menu instanceof ContextMenu) {
          ((ContextMenu) menu).setHeaderTitle("Context menu title");
      }
      menu.clear();
      inflater.inflate(R.menu.menu, menu);
      for (int i = 0; i < menu.size(); i++) {
          menu.getItem(i).setOnMenuItemClickListener(mOnMenuItemClickListener);
      }
     
  }
  
  private final OnMenuItemClickListener mOnMenuItemClickListener = new OnMenuItemClickListener() {
      @Override
      public boolean onMenuItemClick(MenuItem menuItem) {
          boolean result = false;
          final int id = menuItem.getItemId();
          if (menuItem.getTitle().equals("order")) {
        	  mCallback.show_boxf(0);
		  }
          if (menuItem.getTitle().equals("preorder")) {       
        	  mCallback.show_boxf(1);
          }
          if (menuItem.getTitle().equals("subscribe")) {        	  
        	  mCallback.show_boxf(2);
          }
          //  System.out.println("onMenuItemClick id========="+id);
          return true;
      }
  };
  
  
  class adapter2 extends BaseAdapter{

		
		List<Box> list;
		public adapter2() {
			super();
			// TODO Auto-generated constructor stub
		}
	    
		 public void refresh(List<Box> list) {    
	         this.list = list;    
	                 notifyDataSetChanged();    
	        } 
		
		public List<Box> getList() {
			return list;
		}



		public void setList(List<Box> list) {
			this.list = list;
		}



		public adapter2(List<Box> list) {
			super();
			this.list = list;
		}
		 public void clear(){
	    	   list.clear();
	       }

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			System.out.println("arg0---------------"+arg0);
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.four_layout_list_item, arg2);
			}
			
			
			Box i = (Box) getItem(arg0);
			AQuery aq = aq2.recycle(arg1);
		    aq.id(R.id.four_layout_list_item_name).text(i.getEntity().getName());
		    aq.id(R.id.four_layout_list_item_price).text("￥"+i.getEntity().getPrice());
		    aq.id(R.id.four_layout_list_item_num).text(String.valueOf(i.getNum()));
		    aq.id(R.id.four_layout_list_item_tatalprice).text(String.valueOf(i.getPrice()));
		    CheckBox checkb = (CheckBox) aq.id(R.id.four_layout_list_item_check).getCheckBox();
		    checkb.setOnClickListener(FourFragmentPreorder.this); 
		  //  checkb.setOnCheckedChangeListener(FourFragmentPreorder.this);
		    checkb.setTag(arg0);
		    if (!check_list.contains(checkb)) {
				check_list.add(checkb);
			}
			String tbUrl = i.getEntity().getPre_pic().replace("localhost", Whm_app.api_url);		
			if(aq.shouldDelay(arg0, arg1, arg2, tbUrl)){
				aq.id(R.id.four_layout_list_item_imageview).clear();
			}else{
				aq.id(R.id.four_layout_list_item_imageview).image(tbUrl, true, true, 100, R.drawable.ic_launcher, null,0, 0);
			}
			
			return arg1;
		}
		
		
	}


  @Override
  public void onAttach(Activity activity) {
      super.onAttach(activity);

      // This makes sure that the container activity has implemented
      // the callback interface. If not, it throws an exception.
      try {
          mCallback = (box_Selection) activity;
      } catch (ClassCastException e) {
          throw new ClassCastException(activity.toString()
                  + " must implement OnHeadlineSelectedListener");
      }
  }



public void set_func(){
	//System.out.println("======preorder=====set_func===============");
	//Toast.makeText(getActivity(), String.valueOf("sp==null"+sp==null), 1000).show();
	if (sp!=null) {
		 getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					/*System.out.println(sp.getSelectedItem().toString());
					System.out.println(sp.getSelectedItemPosition());
					
					sp.setSelection(1);
					sp.setVisibility(View.GONE);
					System.out.println("=="+sp.getSelectedItem().toString());
					System.out.println("=="+sp.getSelectedItemPosition());*/
				}
			});
	}
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
		long id) {
	// TODO Auto-generated method stub
	Toast.makeText(getActivity(), "p ==="+position, 1000).show();
	
	
}






@Override
public void onNothingSelected(AdapterView<?> parent) {
	// TODO Auto-generated method stub
	
}


boolean is_check=true;
List<String> ids=new ArrayList<String>();
List<Box> ids_box=new ArrayList<Box>();



@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	switch (v.getId()) {  
    case R.id.four_layout_btn_sure:
    	buy_sure();
    	break;
    case R.id.four_layout_btn_all:
    	btn_all();
    	break;
    case R.id.four_layout_btn_del:
    	btn_del();
    	break;
    case R.id.four_layout_list_item_check:
    final CheckBox ch=(CheckBox) v;	
	int pos=(Integer) ch.getTag();
	ch.setFocusable(false);
	ch.setFocusableInTouchMode(false);
	Box box=adap2.getList().get(pos);
	String id=box.getCollname()+"_"+box.getEntity().getId();
	if (ch.isChecked()) {
		
		if (!ids.contains(id)) {
			ids.add(id);
		}
		if (!ids_box.contains(box)) {
			ids_box.add(box);
		}
	}else{
		ids.remove(id);
		ids_box.remove(box);
	}

	Toast.makeText(getActivity(), id+" "+ids.size()+" "+ids_box.size(), 1000).show();
	break;
    default:  
        break;  
    }  
}
public void show_dialog(boolean b){
	if (dialog==null) {
		dialog = new ProgressDialog(getSupportActivity());
	    dialog.setIndeterminate(true);
	    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    dialog.setMessage("post");
	}
	if (b) {
		dialog.show();
	}else{
		dialog.dismiss();
	} 
    
}


public void btn_all(){
	
	System.out.println("check_list.size()======="+check_list.size());
	for(final CheckBox checkb:check_list){
		int pos=(Integer) checkb.getTag();
		Box box=adap2.getList().get(pos);
		String id=box.getCollname()+"_"+box.getEntity().getId();
	
		
		if (is_check) {
			 getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					checkb.setChecked(true);
					//System.out.println("checkb.isChecked() ======="+checkb.isChecked());
				}
			});
			
			
			
			
			if (!ids.contains(id)) {
				ids.add(id);
			}
			if (!ids_box.contains(box)) {
				ids_box.add(box);
			}
			
		}else{
			 getActivity().runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						checkb.setChecked(false);
						
					}
				});
						
			ids.remove(id);
			ids_box.remove(box);
		}
		
	}
if (is_check) {
		
		is_check=false;
	}else{
		is_check=true;
	}
System.out.println("ids======="+JSONObject.toJSONString(ids));
System.out.println("ids_box.size()======="+ids_box.size());
	
}



public void btn_del(){
	if (!ids.isEmpty()) {
		Map<String, Object> params = new HashMap<String, Object>();
	    params.put("type", 2);
	    params.put("ids", JSONObject.toJSONString(ids));
	  
	    System.out.println("btn_del ids===="+JSON.toJSONString(ids));
	    String url="http://"+Whm_app.api_url+":9000/api/buy_del_func";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(FourFragmentPreorder.this, "buy_del_func_result");

	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
	String cookiename=sp.getString("cookie_name",null);
	String cookievalue=sp.getString("cookie_value",null);
	if (cookiename!=null&&cookievalue!=null) {
		cb.cookie(cookiename,cookievalue);               
	}else{
		
	}
	
	show_dialog(true);	
	cb.params(params);

	aq.ajax(cb);
	}else{
		
		
		Toast.makeText(getActivity(), "no selected", 1000).show();
	}
	
}

public void buy_del_func_result(String url, String r, AjaxStatus status){
	show_dialog(false);
	 if (status.getCode()==200) {
		 adap2.getList().removeAll(ids_box);
		
		// check_list.clear();
		 System.out.println("adap2.getList() "+JSONObject.toJSONString(adap2.getList()));
		 System.out.println("ids_box "+JSONObject.toJSONString(ids_box));
		 
		  getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					 
					 
				
					
					 num=0;
					 price=0;
					 for(Box b: adap2.getList()){
						  num=num+b.getNum();
						  price=price+b.getPrice();
						  
					  };
					 num_t.setText(String.valueOf(num));
					 price_t.setText(String.valueOf(price));
					 Toast.makeText(getActivity(), "adap2.getList().size()="+adap2.getList().size()+" num="+num+" price="+price, 3000).show();
					// adap2.notifyDataSetChanged();
					check_list.clear();
					ids.clear();
					ids_box.clear();
					adap2.refresh(adap2.getList());
					adapter1.notifyDataSetChanged();
					
				}
			});
		
		  
	 }else{
		 Toast.makeText(getActivity(), "parse error", 1000).show();
	 }
	
	
}

public void refresh_list(){
	  getActivity().runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			
				 num=0;
					price=0;
					 num_t.setText(String.valueOf(num));
					 price_t.setText(String.valueOf(price));
				 adap2.clear();
				 adap2.notifyDataSetChanged();
				 adapter1.notifyDataSetChanged();
			
			}
		});
	
}

public void refresh(){
	show_dialog(true);
	init();
	
}


public void buy_sure(){
	
	  Map<String, Object> params = new HashMap<String, Object>();
	    params.put("type", 1);
	    params.put("tag", 2);
	    params.put("address_id", add.getId());
	    params.put("date", datelist.get(sp.getSelectedItemPosition()));
	  
	    System.out.println("buy_sure===="+JSON.toJSONString(params));
	    String url="http://"+Whm_app.api_url+":9000/api/buy_sure_func";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(FourFragmentPreorder.this, "sure_func_result");
	
	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
	String cookiename=sp.getString("cookie_name",null);
	String cookievalue=sp.getString("cookie_value",null);
	if (cookiename!=null&&cookievalue!=null) {
		cb.cookie(cookiename,cookievalue);               
	}
	show_dialog(true);	
	cb.params(params);
	
	aq.ajax(cb);
	
}


public void sure_func_result(String url, String r, AjaxStatus status){
	  show_dialog(false);
	  System.out.println("sure_func_result========="+r);
	  System.out.println("sure_func_result status.getCode()========="+status.getCode());
	  System.out.println("sure_func_result url========="+url);
	  if (status.getCode()==200) {
		
		 String re=JSON.parseObject(r).getString("result");
		 if (re.equals("ok")) {
			refresh_list();
		}else if(re.equals("login_error")){
			
			Toast.makeText(getActivity(), String.valueOf("login error,please again"), 1000).show();
		}
		 
	 }else{		 
		 Toast.makeText(getActivity(), String.valueOf("post error,please again"), 1000).show();
	 }
}


 
}
